%{
Get all the results together
This takes a LOT of time! Consider pre-allocating space for
stata_matrix_all
%}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% All the calibration Files into One for Stata %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

stata_matrix_all = [];

for results= 1:57288 % change this number to the total number of parameter combinations that are candidates for baseline calibration
  %  eval(['cd run',num2str(results),';']);
    filename = strcat('results/resultsBaseline',num2str(results),'.mat');
    disp(filename)
    if exist(filename, 'file')   
        % read in the file
        eval(['load results/resultsBaseline',num2str(results)]);
        disp(strcat('Mu:', num2str(mu_fc),'; Sigma: ',num2str(sigma_fc),'; Entry Cost: ',num2str(c_e),'; Delta: ',num2str(delt)));
        % compute seller value
        agent_match_prob = (repmat((Ne').*dist',1,kw).*w_mat) ./ repmat(sum(repmat((Ne').*dist',1,kw).*w_mat,1),ks,1); % probability of matching with each agents
        Vs = zeros(1,9);
        found=0;
        while found==0
            EVs = repmat((T*Vs')',ks,1).*w_mat;% expected future value
            Vs_new = sum(agent_match_prob.*(repmat(Sale_p,1,kw).*repmat(Price_vec',1,kw).*(1-2*psi) + bet*(1-repmat(Sale_p,1,kw)).*EVs),1);
            if max(abs((Vs_new-Vs)./Vs))<0.001
                found=1;
            end
            Vs = Vs_new;
        end
        
        % listing accumulation
        num_bs = Ne+Nb;
        b = regress(num_bs',State(1,:)');
        
        % need mode time
        fail = nmain==1000;
        
        % save parameters and listing accumulation moment
        parameters = [mu_fc sigma_fc c_e delt b fail]; % what's b? added delta 
        parameters = repmat(parameters,size(Ne,2),1);
        
        % save output
        stata_matrix = [State(1,:)' State(3,:)' (Ne)' (Nb)' Sale_p EProfit policy dist' lambd(State(3,:))' Vs(State(3,:))' Buy_p parameters];
        stata_matrix_all = [stata_matrix_all; stata_matrix];
    end
  %  cd ..
end

save calibration_results_stata.mat stata_matrix_all
csvwrite('calibration_results_data.csv',stata_matrix_all);







